//
//  NetworkManager.swift
//  WEIBO
//
//  Created by 谢曦 on 2017/5/6.
//  Copyright © 2017年 谢曦. All rights reserved.
//

import UIKit
import AFNetworking
enum WBHTTPMethod {
    case GET
    case POST
}

class NetworkManager: NSObject {
     // MARK: -   创建单例
    let manager : AFHTTPSessionManager = AFHTTPSessionManager.init()

    static let shareInstance: NetworkManager = {
    
        // 实例化对象
        let instance = NetworkManager()
        instance.manager.requestSerializer  = AFHTTPRequestSerializer();
        instance.manager.responseSerializer = AFHTTPResponseSerializer();
        /*! 设置请求超时时间 */
        instance.manager.requestSerializer.timeoutInterval=30
        return instance
    }()
    
    
    
    
    func request(type:WBHTTPMethod,url:String,param:[String:AnyObject]?,success:@escaping (_ response:[String:AnyObject])->(),failure:@escaping (_ error:Error)->()) -> () {
        
        var  params = param
        if  params != nil && !url.isEqual("https://api.weibo.com/oauth2/access_token") {
            params?["access_token"] = accessToken as AnyObject
           
        }
        print(params)
        if (type == .GET) {
        NetworkManager.shareInstance.manager.get(url, parameters: params, progress: nil, success: { (_, responseObject) in
            
            //如果responseObject不为空时
            if  let result = responseObject as? Data  {
                // Notice the need to use try here
                let a = try?JSONSerialization.jsonObject(with: result, options:JSONSerialization.ReadingOptions.mutableLeaves)
                print(a)
                success(a as! [String:AnyObject])
       
            }

                }, failure: { (_, error) in
          
         failure(error)
        })
        }
        
        if(type == .POST){
        
        NetworkManager.shareInstance.manager.post(url, parameters: param, progress: nil, success: { (_, responseObject) in
            //如果responseObject不为空时
            if  let result = responseObject as? Data  {
                // Notice the need to use try here
                let a = try?JSONSerialization.jsonObject(with: result, options:JSONSerialization.ReadingOptions.mutableLeaves)
                print(a)
                success(a as! [String:AnyObject])
                
                
                
            }
        }, failure: { (_, error) in
           
            failure(error)
        })
        
        }
    }

      
//    /// 用户账户的懒加载属性
//    lazy var userAccount = WBUserAccount()
//
//    /// 用户登录标记[计算型属性]
//    var userLogon: Bool {
//        return userAccount.access_token != nil
//    }

}

